package cn.moonspace.flowerowner.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.moonspace.flowerowner.entities.Manager;
import cn.moonspace.flowerowner.exception.DriverException;
import cn.moonspace.flowerowner.form.LoginForm;
import cn.moonspace.flowerowner.service.ManagerService;

@Controller
public class ManagerController extends BaseController{
	@RequestMapping(value = { "/back/login" }, method = { RequestMethod.GET })
	public String login(
			HttpServletRequest request,HttpServletResponse response,
			HttpSession session,ModelMap model) throws Exception{
		model.addAttribute("loginForm", new LoginForm());
		return "/back/login";
	}
	
	@RequestMapping(value = { "/back/login" }, method = { RequestMethod.POST })
	public @ResponseBody Object postLogin(
			@Valid @ModelAttribute("loginForm") LoginForm loginForm, 
			Errors errors, HttpSession session) {
		JSONObject result = new JSONObject();
		JSONArray list = new JSONArray();
		Map<String, String> errorMap = new HashMap<String, String>();
		
		// 错误校验
		if(errors.hasErrors()) {
			for(FieldError error : errors.getFieldErrors()) {
				errorMap.put("field", error.getField() + "Help");
				errorMap.put("message", error.getDefaultMessage());
				list.add(errorMap);
			}
			result.put("error", list);
			return result;
		}
		
		switch (managerService.login(loginForm)) {
		case ManagerService.USERNAME_NOT_FOUND:
			errorMap.put("field", "usernameHelp");
			errorMap.put("message", "用户名不存在");
			list.add(errorMap);
			result.put("error", list);
			return result;
		case ManagerService.PASSWORD_ERROR:
			errorMap.put("field", "passwordHelp");
			errorMap.put("message", "密码错误");
			list.add(errorMap);
			result.put("error", list);
			return result;
		default:
			// 登录成功
			result.put("message", "success");
			session.setAttribute("Manager", managerRepository.findByUsername(loginForm.getUsername()));
			return result;
		}
	}
	
	@RequestMapping(value="/back/index",method=RequestMethod.GET) 
	public String backIndex(HttpSession session, HttpServletResponse response, ModelMap model) {
		return "/back/index";
	}
	
	@RequestMapping(value="/back/verify", method=RequestMethod.GET) 
	public String backGalleryForVerifyGet(HttpSession session, HttpServletResponse response, ModelMap modelMap, @RequestParam String status) throws DriverException {
		modelMap.put("status", status);
		return "/back/verify";
	}
	
	@RequestMapping(value="/back/galleryVerify", method=RequestMethod.POST) 
	public @ResponseBody Object backGalleryForVerifyPost(HttpSession session, HttpServletResponse response, ModelMap modelMap, @RequestParam String status,
			@RequestParam int pages, @RequestParam int pageSize) throws DriverException {
		modelMap.put("status", status);
		return uploadService.findUploadsForBack("".equals(status) ? null : Integer.valueOf(status), pages, pageSize, null);
	}
	
	@RequestMapping(value="/back/verify",method=RequestMethod.POST) 
	public JSONObject backVerify(HttpSession session, HttpServletResponse response, ModelMap model, String uploadID, String uploadStatus) {
		return uploadService.updateUploadStatus(Long.valueOf(uploadID), Integer.valueOf(uploadStatus));
	}

	@RequestMapping(value="/back/changePass",method=RequestMethod.POST) 
	public @ResponseBody Object backChangePass(HttpSession session, HttpServletResponse response, ModelMap model, String oldPass, String newPass) {
		JSONObject result = new JSONObject();
		Manager manager = (Manager)session.getAttribute("Manager");
		switch (managerService.changePass(manager, oldPass, newPass)) {
			case ManagerService.CHANGE_SUCCESS:
				session.setAttribute("Manager", manager);
				result.put("code", ManagerService.CHANGE_SUCCESS);
				result.put("result", "修改成功");
				break;
			case ManagerService.CHANGE_ERROR:
				result.put("code", ManagerService.CHANGE_ERROR);
				result.put("result", "原密码错误，修改失败");
				break;
		}
		return result;
	}
	
	@RequestMapping(value="/back/car", method=RequestMethod.GET) 
	public String backCarListInit(HttpSession session, HttpServletResponse response, ModelMap modelMap) throws DriverException {
		JSONObject json = carService.findCars(0,10);
		modelMap.put("cars", json);
		modelMap.put("carPages", (carRepository.count()-1)/10+1);
		return "/back/car";
	}
	
	@RequestMapping(value="/back/car", method=RequestMethod.POST) 
	public @ResponseBody Object backCarList(HttpSession session, HttpServletResponse response, ModelMap modelMap, int pages, int pageSize) throws DriverException {
		return carService.findCars(pages-1, pageSize);
	}

	@RequestMapping(value="/back/regulation", method=RequestMethod.GET) 
	public String backRegulationListInit(HttpSession session, HttpServletResponse response, ModelMap modelMap) throws DriverException {
		JSONObject json = regulationService.findRegulations(0,10);
		modelMap.put("regulations", json);
		modelMap.put("regulationPages", (regulationRepository.count()-1)/10+1);
		return "/back/regulation";
	}
	
	@RequestMapping(value="/back/regulation", method=RequestMethod.POST) 
	public @ResponseBody Object backRegulationList(HttpSession session, HttpServletResponse response, ModelMap modelMap, int pages, int pageSize) throws DriverException {
		return regulationService.findRegulations(pages-1, pageSize);
	}

	@RequestMapping(value = "/back/delUpload", method = RequestMethod.POST)
	public @ResponseBody Object backDelUpload(HttpSession session, HttpServletResponse response, HttpServletRequest request, @RequestParam Long id) throws DriverException {
		String realPath = request.getSession().getServletContext().getRealPath(UPLOAD_PICTURE_PATH);
		return uploadService.delUpload(id, realPath);
	}
	
	@RequestMapping(value="/back/logout",method=RequestMethod.GET) 
	public String logout(HttpSession session,ModelMap model) {
		session.removeAttribute("Manager");
		model.addAttribute("loginForm", new LoginForm());
		return "/back/login";
	}
}
